
// 登录
export default defineEventHandler(async (event) => {
    try {
        const { username, password } = await readBody(event) || {};
        // 1. 验证参数
        loginSchema({ username, password });
        // 2. 查找用户 (伪代码)
        const db = useDatabase();
        const { rows } = await db.sql`SELECT id, username, email, phone, avatar, status, created_time as "createdTime", updated_time as "updatedTime" FROM user WHERE username = ${username} AND password = ${password}`;
        const user = rows[0] as unknown as User;
        if (!user) {
            return errorResponse("用户名或密码错误");
        }
        // 3. 生成 Token
        const accessToken = generateAccessToken(Object.assign({ type: 'access' as const }, user))
        const refreshToken = generateRefreshToken(Object.assign({ type: 'refresh' as const }, user))

        // 3. 设置 HTTP-only Cookie (可选)
        setCookie(event, 'refresh_token', refreshToken, {
            httpOnly: true,
            secure: true,
            sameSite: 'strict',
            maxAge: 60 * 60 * 24 * 7 // 7天
        })

        return {
            accessToken,
            user
        }
    } catch (error) {
        console.error('login error', error);
        return catchErrorResponse(error)
    }
})